<?php
namespace library\Session;

/**
 * Klasa sterownika do obsługi sesji
 *
 * @author Damian
 */
class Server extends Driver{
    /**
     * @readwrite
     */
    protected $prefix="app_";
    public function __construct($options = array()) {
        parent::__construct($options);
        if(!isset($_SESSION)) {
             session_start ();
        }
    }
    /**
     * funkcja pobiera wartość z sesji
     * @param type $key
     * @return mixed <p>element znajdujący się w sesji pod kluczem $key</p>
     * @return null <p> jeśli dany element w sesji nie istnieje</p>
     */
    public function get($key){
        $prefix = $this->getPrefix();
        try{
            $elem = \library\ArrayMethods::getElement($prefix.$key, $_SESSION);
            $decrypted = \library\StringMethods::decrypt($elem);
            $decoded = base64_decode($decrypted);
            $deserialized = unserialize($decoded); 
            return $deserialized;
        }catch (\library\exceptions\ExceptionNotFound $e){
            return null;
        }
    }
    public function set($key,$value){
        $prefix = $this->getPrefix();
        $serialized = serialize($value);
        $encoded = base64_encode($serialized);
        $encrypted = \library\StringMethods::encrypt($encoded);        
        $_SESSION[$prefix.$key]= $encrypted;
       return $this;
    }
    public function erase($key){
        if ($this->get($key)){
            $prefix = $this->getPrefix();
            unset($_SESSION[$prefix.$key]);
        }
        return $this;
    }
    public function __destruct() {
        session_commit();
    }
}
